package com;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import sun.swing.StringUIClientPropertyKey;

import java.util.List;

/**
 * @ClassName DemoListDomains
 * @Deacription TODO
 * @Author CG-C34
 * @Date 2021/3/18 10:25
 * @Version 1.0
 **/
@Component
@Slf4j
public class DemoListDomains {

    private static IAcsClient client = null;
    private String regionId = "cn-hangzhou";
    private static String ip = "";

    @Value("${AccessKeyID}")
    private String accessKeyId;
    @Value("${AccessKey}")
    private String accessKeySecret;
    @Value("${DomainName}")
    private String domainName;

    /**
     * @param
     * @return void
     * @Author zzz
     * @Description //TODO 定时任务 60秒查询一次当前公网ip,对比旧的公网ip和阿里云dns里的ip,如果不同就更新解析记录
     * @Date 15:17 2021/3/18
     */
    @Scheduled(fixedDelay = 60000)
    public void DDNS() {
        log.info("进入DDNS");
        //获取ip地址
        String newIp = getIp();
        log.info("newIp:" + newIp);
        log.info("原ip：" + ip);
        if (StringUtils.isNotBlank(newIp) && !ip.equals(newIp)) {
            ip = newIp;
            System.out.println("yml配置：");
            System.out.println("AccessKeyID："+accessKeyId);
            System.out.println("AccessKey："+accessKeySecret);
            System.out.println("DomainName：" + domainName);
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            // 若报Can not find endpoint to access异常，请添加以下此行代码
            // DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Alidns", "alidns.aliyuncs.com");
            client = new DefaultAcsClient(profile);

            DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
            request.setDomainName(domainName);
            // describeRegionsRequest.setProtocol(ProtocolType.HTTPS); //指定访问协议
            // describeRegionsRequest.setAcceptFormat(FormatType.JSON); //指定api返回格式
            // describeRegionsRequest.setMethod(MethodType.POST); //指定请求方法
            // describeRegionsRequest.setRegionId("cn-hangzhou");//指定要访问的Region,仅对当前请求生效，不改变client的默认设置。
            try {
                DescribeDomainRecordsResponse response = client.getAcsResponse(request);
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(response));
                JSONArray domainRecords = jsonObject.getJSONArray("domainRecords");
                JSONObject domainRecord = JSONObject.parseObject(domainRecords.get(0).toString());
                log.info("RecordId:" + domainRecord);
                String value = domainRecord.getString("value");
                String RecordId = domainRecord.getString("recordId");
                String RR = domainRecord.getString("rR");
                String type = domainRecord.getString("type");
                System.out.println("阿里云DNS记录值:" + value);
                System.out.println("阿里云DNS记录id:" + RecordId);
                System.out.println("阿里云DNS记录RR:" + RR);
                System.out.println("阿里云DNS记录type:" + type);
                if (!value.equals(ip)) {
                    UpdateDomainRecordRequest updateDomainRecordRequest = new UpdateDomainRecordRequest();
                    updateDomainRecordRequest.setRecordId(RecordId);
                    updateDomainRecordRequest.setRR(RR);
                    updateDomainRecordRequest.setType(type);
                    updateDomainRecordRequest.setValue(ip);
                    try {
                        UpdateDomainRecordResponse updateDomainRecordResponse = client.getAcsResponse(updateDomainRecordRequest);
                        log.info(new Gson().toJson(updateDomainRecordResponse));
                    } catch (ServerException e) {
                        e.printStackTrace();
                    } catch (ClientException e) {
                        System.out.println("ErrCode:" + e.getErrCode());
                        System.out.println("ErrMsg:" + e.getErrMsg());
                        System.out.println("RequestId:" + e.getRequestId());
                    }
                }

            } catch (ServerException e) {
                e.printStackTrace();
                log.info(e.getMessage());
            } catch (ClientException e) {
                e.printStackTrace();
                log.info(e.getMessage());
            } finally {

            }


        }
    }


    public static String getIp() {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://www.3322.org/dyndns/getip");
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String ip = EntityUtils.toString(entity, "UTF-8").trim();
            System.out.println("current ip: " + ip);
            return ip;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("getip failed" + e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }
}
